<?php

namespace app\controller;

use app\BaseController;
use OpenImSdk\Client;
use think\facade\Request;
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Validate;
use think\facade\Db;
use Ramsey\Uuid\Uuid;
//登录注册控制器
class Index extends BaseController
{

    public function config() {
        //获取配置
        return json(['code' => 200, 'msg' => 'sss', 'data'=>[
            'IMApi'=>'http://www.tracecare.cn:10002',
            'IMAddr'=>'ws://www.tracecare.cn:10001'
        ]]);
    }

    public function index() 
    {
        // 验证参数
        $validate = Validate::rule([
            'loginType' => 'require|in:0,1',
            'appleUserId' => 'requireIf:loginType,0',
            'email' => 'requireIf:loginType,1|email',
            'nickName' => 'string|max:20',
            'code' => 'requireIf:loginType,1|string|max:6',
        ]);
        
        $params = $this->request->post();
        if (!$validate->check($params)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        Db::startTrans();
        try {
            $email = $params['email'] ?? '';
            $user = null;

            if ($params['loginType'] == 0) {
                $user = $this->handleAppleLogin($params, $email);
            } else {
                $user = $this->handleEmailLogin($params, $email);
            }

            if (!$user) {
                $user = $this->createNewUser($params, $email);
            } else {
                $user = $this->updateExistingUser($params, $user);
            }

            Db::commit();
            
            $haveBasicProfile = $user['nickname'] && $user['avatar'] ? true : false;
            // $config = [
            //     'host'=>'http://www.tracecare.cn:10002',
            //     'secret'=>'openIM123'
            // ];
            // $IM = new Client($config);
            // $nickname = $user['nickname'] ?: '';
            // $avatar = $user['avatar'] ?: '';
            // $IM->auth->userRegister($user['user_number'], $nickname, $avatar);
            // $platform = $this->request->header('os') ?: 1;
            // $response = $IM->auth->getUserToken($user['user_number'], $platform);
            return json([
                'code' => $haveBasicProfile ? 200 : 201,
                'msg' => 'success',
                'data' => [
                    'userNumber' => $user['user_number'],
                    'token' => $user['token'],
                ]]);
        } catch (\Exception $e) {
            Db::rollback();
            return json([
                'code' => 500,
                'msg' => '服务器错误：' . $e->getMessage()
            ]);
        }
    }

    private function handleAppleLogin($params, $email)
    {
        $user = Db::name('think_users')->where('user_apple_user_id', $params['appleUserId'])->find();
        if (!$user && !empty($email)) {
            $existingUser = Db::name('think_users')->where('email', $email)->find();
            if ($existingUser) {
                Db::name('think_users')->where('id', $existingUser['id'])->update([
                    'user_apple_user_id' => $params['appleUserId'],
                    'update_time' => date('Y-m-d H:i:s'),
                    'last_login_time' => date('Y-m-d H:i:s'),
                    'token' => Uuid::uuid4()->toString()
                ]);
                return Db::name('think_users')->where('id', $existingUser['id'])->find();
            }
        }
        return $user;
    }

    private function handleEmailLogin($params, $email)
    {
        if (empty($email)) {
            throw new \Exception('邮箱不能为空');
        }
        if ($email == "617076272@qq.com" && $params['code'] == "123456") {
            # code...
            //测试账号
            return Db::name('think_users')->where('email', $email)->find();
        }
        $verifyCode = Db::name('think_verify_code')
            ->where('email', $email)
            ->where('code', $params['code'])
            ->where('is_used', 0)
            ->where('expire_time', '>', date('Y-m-d H:i:s'))
            ->find();
        
        if (!$verifyCode) {
            throw new \Exception('验证码无效或已过期');
        }

        Db::name('think_verify_code')
            ->where('id', $verifyCode['id'])
            ->update([
                'is_used' => 1,
                'update_time' => date('Y-m-d H:i:s')
            ]);

        return Db::name('think_users')->where('email', $email)->find();
    }

    private function createNewUser($params, $email)
    {
        $userData = [
            'user_number' => 'U' . date('YmdHis') . rand(1000, 9999),
            'email' => $email,
            'nickname' => $params['nickName'] ?? ('用户' . substr(uniqid(), -6)),
            'token' => Uuid::uuid4()->toString(),
            'create_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'last_login_time' => date('Y-m-d H:i:s'),
            'uuid' => Uuid::uuid4()->toString(),
        ];
        
        if ($params['loginType'] == 0) {
            $userData['user_apple_user_id'] = $params['appleUserId'];
        }
        
        $userId = Db::name('think_users')->insertGetId($userData);
        return Db::name('think_users')->where('id', $userId)->find();
    }

    private function updateExistingUser($params, $user)
    {
        $updateData = [
            'last_login_time' => date('Y-m-d H:i:s'),
            'update_time' => date('Y-m-d H:i:s'),
            'token' => Uuid::uuid4()->toString()
        ];
        
        if (!empty($params['nickName'])) {
            $updateData['nickname'] = $params['nickName'];
        }
        
        Db::name('think_users')->where('id', $user['id'])->update($updateData);
        return Db::name('think_users')->where('id', $user['id'])->find();
    }
    
    public function sendEmailCode()
    {
        ini_set('max_execution_time','100');
        // 验证参数
        $validate = Validate::rule([
            'email' => 'require|email',
        ]);
        
        $params = $this->request->post();
        if (!$validate->check($params)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }

        Db::startTrans();
        try {
            // 检查是否频繁发送
            $lastCode = Db::name('think_verify_code')
                ->where('email', $params['email'])
                ->where('create_time', '>', date('Y-m-d H:i:s', strtotime('-1 minute')))
                ->find();
                
            if ($lastCode) {
                return json(['code' => 400, 'msg' => '发送太频繁，请稍后再试']);
            }

            // 生成验证码
            $code = sprintf('%06d', random_int(0, 999999));
            
            // 保存验证码
            $data = [
                'email' => $params['email'],
                'code' => $code,
                'create_time' => date('Y-m-d H:i:s'),
                'expire_time' => date('Y-m-d H:i:s', strtotime('+5 minutes')),
                'ip' => $this->request->ip()
            ];
            // 发送邮件
            try {
                $mail = new PHPMailer(); // create a new object
                $mail->IsSMTP(); // enable SMTP
                $mail->SMTPAuth = true; // authentication enabled
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // secure transfer enabled REQUIRED for Gmail
                $mail->Host = config('mail.host');
                $mail->Port = config('mail.port'); // or 587
                $mail->IsHTML(true);
                $mail->Username = config('mail.username');
                $mail->Password = config('mail.password');
                $mail->SetFrom(config('mail.from.address'));
                $mail->Subject = "Thanks for registering";
                $mail->Body = "Dear " . $params['email'] . ",<br><br> Thanks for Logging in PKLove, Your Verification code is: <b>" . $code . "</b><br><br> This code is valid for 5 minutes.<br><br> Regards,<br> PKLove Team";
                $mail->AddAddress($params['email']);
                $mail->Send();
                Db::name('think_verify_code')->insert($data);
                Db::commit();
                return json(['code' => 200, 'msg' => '验证码已发送']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 500, 'msg' => '邮件发送失败：' . $e->getMessage()]);
            }
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 500, 'msg' => '服务器错误：' . $e->getMessage()]);
        }
    }

    public function logout()
{
    // 获取 Bearer Token
    $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }
    
    $token = $matches[1];
    
    try {
        Db::startTrans();
        
        // 清除用户token
        $result = Db::name('think_users')
            ->where('token', $token)
            ->update([
                'token' => null,
                'update_time' => date('Y-m-d H:i:s')
            ]);
            
        if ($result) {
            Db::commit();
            return json([
                'code' => 200,
                'msg' => '退出成功'
            ]);
        } else {
            throw new \Exception('用户不存在或已退出');
        }
        
    } catch (\Exception $e) {
        Db::rollback();
        return json([
            'code' => 500,
            'msg' => '退出失败：' . $e->getMessage()
        ]);
    }
    }

    public function unregist()
{
    // 获取 Bearer Token
    $token = Request::header('Authorization');
    if (empty($token) || !preg_match('/^Bearer\s+(.+)$/i', $token, $matches)) {
        return json(['code' => 401, 'msg' => '未授权访问']);
    }

    $token = $matches[1];

    try {
        Db::startTrans();

        // 查找用户
        $user = Db::name('think_users')->where('token', $token)->find();
        if (!$user) {
            return json(['code' => 404, 'msg' => '用户不存在']);
        }

        // 删除用户相关数据
        Db::name('think_users')->where('id', $user['id'])->delete();
        Db::name('think_verify_code')->where('email', $user['email'])->delete();
        // 如果有其他关联表，也需要在这里删除相关数据

        Db::commit();

        return json([
            'code' => 200,
            'msg' => '账户已成功注销'
        ]);
    } catch (\Exception $e) {
        Db::rollback();
        return json([
            'code' => 500,
            'msg' => '注销失败：' . $e->getMessage()
        ]);
    }
}
}